/*
 * @Date: 2025-08-07 15:02:33
 * @LastEditTime: 2025-08-07 16:39:36
 */
const mysql = require('mysql2/promise');
require('dotenv').config();

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'data_dashboard',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

async function initDB() {
  const connection = await pool.getConnection();
  try {
    await connection.query(`
      CREATE TABLE IF NOT EXISTS halls (
        id INT AUTO_INCREMENT PRIMARY KEY,
        hall_name VARCHAR(255) NOT NULL COLLATE 'utf8mb4_0900_ai_ci',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE INDEX idx_hall_name (hall_name) USING BTREE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
    `);

    await connection.query(`
      CREATE TABLE IF NOT EXISTS data_records (
        id INT AUTO_INCREMENT PRIMARY KEY,
        upload_time DATETIME NOT NULL,
        hall_id INT NOT NULL,
        hall_name VARCHAR(255) NOT NULL COLLATE 'utf8mb4_0900_ai_ci',
        host_name VARCHAR(255) NOT NULL COLLATE 'utf8mb4_0900_ai_ci',
        data_value DECIMAL(10, 2) NOT NULL,
        data_screenshot VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_0900_ai_ci',
        big_head_value DECIMAL(10, 2) NULL DEFAULT NULL,
        big_head_screenshot VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_0900_ai_ci',
        host_hall VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_0900_ai_ci',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_upload_time (upload_time) USING BTREE,
        INDEX idx_hall_name (hall_name) USING BTREE,
        INDEX idx_host_name (host_name) USING BTREE,
        CONSTRAINT fk_hall_id FOREIGN KEY (hall_id) 
          REFERENCES halls (id) 
          ON DELETE RESTRICT ON UPDATE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
    `);

    console.log('数据库表结构初始化成功');
  } catch (error) {
    console.error('数据库表结构初始化失败:', error);
  } finally {
    connection.release();
  }
}

async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
  } catch (error) {
    console.error('数据库连接失败:', error);
    process.exit(1);
  }
}

module.exports = {
  pool,
  initDB,
  testConnection
};